//
//  KVUserAccountViewModel.swift
//  KVBestMicroblog
//
//  Created by 李康卫 on 16/7/21.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit

/**
 负责网络请求
 显现UserAccount的单例管理
 接档归档
*/

class KVUserAccountViewModel: NSObject {
    
    ///单例UserAccount
    static let sharedUserAccountViewModel: KVUserAccountViewModel = KVUserAccountViewModel()
    ///定义一个属性让外界访问
    var userAccount:KVUserAccountModel?
    ///用户是否登录
    var userIsLogin: Bool {
        get{
            return userAccount != nil
        }
    }
    //给userAccount从沙河中加载数据
    override init() {
        super.init()
        userAccount = readUserAccountInfo()
    }
    
    //沙盒路径
    let userAccountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/userAccount.plist")
    //https://api.weibo.com/oauth2/access_token post请求网络数据
    ///网络请求存储数据
    func loadAccessToken(code: String,completedBlock:((erorr: NSError?) -> Void) ) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            "client_id" : client_id,
            "client_secret" : "2af8e32ba8e359a7e62442144ec03609",
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        KVNetworkTool.sharedNetworkTool.POST(urlString, parameters: parameters, progress: nil, success: { (_, response) -> Void in
            //            print(response!)
            //用模型保存一个数组很多地方都会用到所以用一个全局模型
            /*
            "access_token" = "2.00ttMxKGLaI1sC57ab3f866cZlLkRB";
            "expires_in" = 157679999;
            "remind_in" = 157679999;
            uid = 5658671297; */
            let userInfo =  KVUserAccountModel.init(dict: response! as! [String : AnyObject])
            //授权成功能回调到控制器
            completedBlock(erorr: nil)
            //将得到的模型数组进行归档
            self.userAccount = userInfo
            NSKeyedArchiver.archiveRootObject(userInfo, toFile: self.userAccountPath)
            
            }) { (_, error) -> Void in
                completedBlock(erorr: error)
        }
    }
    
    ///加载user的基本信息只单纯的字典转模型
    func loadUserBaseInfo(completedBlock: (error: NSError?) -> Void) {
        
//        access_token	true	string url https://api.weibo.com/2/users/show.json
//        uid	false	int64	需要查询的用户ID。
        
        // 先判断是否有获取access_token  uid
        // MARK: error
        guard let access_token = userAccount?.access_token else {
            print("没有access_token加载失败")
            return
        }
        guard let uid = userAccount!.uid else {
            print("没有uid加载失败")
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        //请求参数
        let parameters: NSDictionary = [
            "access_token": access_token,
            "uid": uid
        ]
        ///加载网络数据
        KVNetworkTool.sharedNetworkTool.GET(urlString, parameters: parameters, progress: { (_) -> Void in}, success: { (_, response) -> Void in
//            print(response)
            let result = response as? NSDictionary
//            取出字典给模型赋值
            let screen_name = result?["screen_name"] as? String
            let avatar_large = result?["avatar_large"] as? String
            self.userAccount?.screen_name = screen_name
            self.userAccount?.avatar_large = avatar_large
//            userAccount!.avatar_large = response!["avatar_large"]
            //赋值给模型
            NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.userAccountPath)
            completedBlock(error: nil)
            }) { (_, error) -> Void in
                completedBlock(error: error)
        }
    }
    
    
    //接档
    func readUserAccountInfo() -> KVUserAccountModel? {
        //读取沙盒数据
       return NSKeyedUnarchiver.unarchiveObjectWithFile(userAccountPath) as? KVUserAccountModel
    }
}
